import java.awt.Cursor;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;

public class MainForm extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	int fWidth = 420;
	int fHeight = 320;
	
	public EW_Profiles profile;
	
	// variables for MainForm
	JTextField jtfTimeInterval = new JTextField();
	JTextField jtfAskCount = new JTextField();
	JLabel jlbTimeLeft = new JLabel("mm:ss");
	// labels for MainForm this should be multilanguage
	JLabel jlbTimeInterval = new JLabel();
	JLabel jlbAskCount = new JLabel();
	JLabel jlbTimeBeforeLesson = new JLabel();
	// actions for MainForm. 
	JButton jbStartLesson = new JButton();
	JButton jbSettings = new JButton();
	JButton jbWordTopics = new JButton();
	JButton jbUploadVocabulary = new JButton();
	JButton jbDownloadVocabulary = new JButton();
	JComboBox jcbTopic = new JComboBox();
	JPanel panel = new JPanel(null);
	Timer   tStartLesson;
	Timer   tEachSecond;
	int timeLeft = 0;
	
	public MainForm() {
		doInitForm();
		this.setVisible(true);
	}
	
	public void changeTimerStatus(){
		if (tStartLesson == null)
			return;
		if (tStartLesson.isRunning()){
			tStartLesson.stop();
			tEachSecond.stop();
		}
		else {
			tStartLesson.start();
			tEachSecond.start();
		}
		
	}

	private void initTimers(){
		timeLeft = profile.getRestTime();
		tStartLesson = new Timer(profile.getRestTime() * 1000, new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				jbStartLesson.doClick();
			}
		});
		tEachSecond = new Timer(1000, new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				timeLeft--;
				String timeFormat = Integer.toString(timeLeft/60) + ":" + Integer.toString(timeLeft%60); 
				jlbTimeLeft.setText(timeFormat);
				if (timeLeft <= 0)
					jbStartLesson.doClick();
			}
		});
		tEachSecond.setRepeats(true);
		tStartLesson.setRepeats(true);
		tEachSecond.start();
		tStartLesson.start();
	}
	
	private void doInitForm() {
		this.setResizable(false);
		profile = new EW_Profiles("");
		EW_Profiles temp = profile.getProfileLoadetByDefoult();
		if (temp != null) {
			profile = temp;
			initTimers();
		}
		// it's should depend for screen resolution and device
		this.setSize(fWidth, fHeight);
		
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		this.setTitle("EW-Learning");
		this.setLayout(null);
		
		setLabelsName();
		int large = (int)(fWidth*0.7);
		int smal = (int)(fWidth*0.27);
		jlbTimeInterval.setBounds(5, 5, large, 25);
		jtfTimeInterval.setBounds(large + 5, 5, smal, 25);
		this.add(jlbTimeInterval);
		this.add(jtfTimeInterval);
		
		jlbAskCount.setBounds(5, 35, large, 25);
		jtfAskCount.setBounds(large + 5, 35, smal, 25);
		this.add(jlbAskCount);
		this.add(jtfAskCount);
		
		jlbTimeBeforeLesson.setBounds(5, 65, large, 25);
		jlbTimeLeft.setBounds(large + 5, 65, smal, 25);
		this.add(jlbTimeBeforeLesson);
		this.add(jlbTimeLeft);

		jbStartLesson.setBounds(5, 105, smal*2, 25);
		jcbTopic.setBounds(smal*2 + 10, 105, smal, 25);
		jbSettings.setBounds(5, 135, smal*2, 25);
		jbWordTopics.setBounds(5, 165, smal*2, 25);
		panel.setBounds(5, 190, large + smal, 75);
		jbUploadVocabulary.setBounds(0, 5, smal*2, 25);
		jbDownloadVocabulary.setBounds(0, 35, smal*2, 25);
		panel.add(jbUploadVocabulary);
		panel.add(jbDownloadVocabulary);
		this.add(jbStartLesson);
		this.add(jbSettings);
		this.add(jbWordTopics);
		this.add(jcbTopic);
		this.add(panel);
		setButtonListeners();
		
	}

	private void setButtonListeners() {
		jbSettings.addActionListener(new ActionListener() {		
			@Override
			public void actionPerformed(ActionEvent e) {
				Frame[] mf = MainForm.getFrames();
				if (mf.length > 0) {
					new SettingsForm((JFrame)mf[0]);
				}
			}
		});
		
		jbStartLesson.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				if (profile.getStudyLanguage().equals("")){
					JOptionPane.showMessageDialog((JFrame)MainForm.getFrames()[0], "Необходимо создать профиль");
					return;
				}
				profile.setRestTime(Integer.decode(jtfTimeInterval.getText()));
				profile.setAskCount(Integer.decode(jtfAskCount.getText()));
				profile.updateCurrentRecord();
				tStartLesson.setInitialDelay(profile.getRestTime() * 1000);
				timeLeft = profile.getRestTime();
				Frame[] mf = MainForm.getFrames();
				if (mf.length > 0) {
					new LessonForm((JFrame)mf[0]);
				}				
			}
		});
		
		jbWordTopics.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				if (profile.getStudyLanguage().equals("")){
					JOptionPane.showMessageDialog((JFrame)MainForm.getFrames()[0], "Необходимо создать профиль");
					return;
				}
				Frame[] mf = MainForm.getFrames();
				if (mf.length > 0) {
					new AddToTopicForm((JFrame)mf[0]);
				}
			}
		});
		
		jbUploadVocabulary.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				if (profile.getStudyLanguage().equals("")){
					JOptionPane.showMessageDialog((JFrame)MainForm.getFrames()[0], "Необходимо создать профиль");
					return;
				}
				EW_BaseSynchronize bs;
				if (jcbTopic.getSelectedIndex() == 0){
					bs = new EW_BaseSynchronize(profile, null);
				} 
				else {
					bs = new EW_BaseSynchronize(profile, new EW_Topic(jcbTopic.getSelectedItem().toString(), profile.getStudyLanguage()));
				}
				bs.uploadVocabulary((JFrame)MainForm.getFrames()[0]);
			}
		});
		
		jbDownloadVocabulary.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				if (profile.getStudyLanguage().equals("")){
					JOptionPane.showMessageDialog((JFrame)MainForm.getFrames()[0], "Необходимо создать профиль");
					return;
				}
				else {
					try{
						EW_BaseSynchronize bs;
						bs = new EW_BaseSynchronize(profile, null);
						bs.downloadVocabulary((JFrame)MainForm.getFrames()[0]);
						fillTopicList();
					}
					finally{
						MainForm.getFrames()[0].setCursor(Cursor.getDefaultCursor());
						JOptionPane.showMessageDialog((JFrame)MainForm.getFrames()[0], "Загрузка справочника завершена");
					}
				}
			}
		});
	}
	
	private void setLabelsName() {
		jlbTimeInterval.setText("секунд между занятиями");
		jlbAskCount.setText("Количество вопросов в упражнении");
		jlbTimeBeforeLesson.setText("Время до начала урока");
		// actions for MainForm. 
		jbStartLesson.setText("Начать урок");
		jbSettings.setText("Настройки");
		jbWordTopics.setText("Словарь");
		jcbTopic.addItem("Все");
		jbUploadVocabulary.setText("Выгрузить словарь");
		jbDownloadVocabulary.setText("Загрузить словарь");
		fillTopicList();
		updateVisualCounts();
	}
	
	private void fillTopicList(){
		if (profile.getStudyLanguage().equals("")){
			return;
		}
		ArrayList<EW_Topic> allTopics = EW_Topic.getTopicList("<>", "''", profile.getStudyLanguage());
		for (EW_Topic ewTopic : allTopics) {
			jcbTopic.addItem(ewTopic.getTopicName());
		}
	}
	
	public void updateVisualCounts(){
		jtfAskCount.setText(((Integer)profile.getAskCount()).toString());
		jtfTimeInterval.setText(((Integer)profile.getRestTime()).toString());	
	}
	
	public void callNewLessonForm(){
		new NewLessonForm(this);
		fillTopicList();
	}
}
